<script setup>
import {ref} from "vue";
import {onAddToFavorites, onLoad, onShareAppMessage, onShareTimeline, onShow} from "@dcloudio/uni-app";
import {getInviteCodeAPI, getReportAPI, getShareAPI} from "../../services/makeMoney";
import {BaseImgUrl, BaseURL} from "../../utils/lshttp";
import {getWxShare} from "../../utils/utils";
import {conUtils} from "../../utils/conUtils";
import {useUserInfoStore} from "../../stores/modules/userInfo";
import {requestAndroidPermission} from "../../js_sdk/wa-permission/permission";
// #ifdef H5
import {useCommonInfoStore} from "../../stores/modules/commonInfo";
import jweixin from 'weixin-js-sdk'

const commonInfoStore = useCommonInfoStore()
// #endif
const userInfoStore = useUserInfoStore()
const list5 = ref([])
const current = ref(0)
const temCod = ref()
const temCodContent = ref()
const reportData = ref({
  money: ''
})
const isZLPoster = ref(false)
const showCopySuccess = ref(false)
onLoad(async (option) => {
  if(option?.url){
    list5.value = [option?.url]
    isZLPoster.value = true
  }else{
    await getInviteCode()
    const res = await getShareAPI()
    if (res.result.length > 0) {
      res.result.forEach((item) => {
        if (!item.startsWith('http')) {
          item = BaseURL + item
        }
      })
    }
    list5.value = res.result
  }
  const reportRes = await getReportAPI()
  reportData.value = reportRes.result
  setWxShare()
  // #ifdef H5
  await wxShare()
  // #endif
})

const getInviteCode = async () => {
  const temCodRes = await getInviteCodeAPI()
  temCod.value = temCodRes.result.invite_code
  temCodContent.value = temCodRes.result.content
}

onShow(async () => {
  shareClick()
})

const setWxShare = (type = "message") => {
  return getWxShare({
    title: reportData.value.money ? '用领食,我总共节省了' + reportData.value.money + '元,快来看看你的吧' : '点外卖用领食周边购，每餐只要0-10元',
    path: "/pages/index/index?parent_id=" + userInfoStore.userInfo.id + "&reseller_id=" + userInfoStore.userInfo.reseller_id,
    type,
  },list5.value[current.value]);
}
// 转发到聊天界面
onShareAppMessage(() => {
  return setWxShare("message");
})

// 转发到朋友圈
onShareTimeline(() => {
  return setWxShare("friend");
})
// 添加到收藏
onAddToFavorites(() => {
  return setWxShare("favorite");
});

const wxShareTip = ref(false)
// H5分享
const wxShare = async () => {
  await commonInfoStore.initJSDKConfig(true)
  console.log(`weqweqweqwe`)
  jweixin.ready(() => {
    //自定义“分享给朋友”及“分享到QQ”按钮的分享内容（1.4.0）
    jweixin.updateAppMessageShareData({
      title: '领食周边购', // 分享标题
      desc: "本地优惠，就在领食", // 分享描述
      link: BaseURL + "/#/?parent_id=" + userInfoStore.userInfo.id, // 分享链接
      imgUrl: list5.value[current.value], // 分享图标
    });
    //自定义“分享到朋友圈”及“分享到QQ空间”按钮的分享内容（1.4.0）
    jweixin.updateTimelineShareData({
      title: '领食周边购', // 分享标题
      link: BaseURL + "/#/?parent_id=" + userInfoStore.userInfo.id, // 分享链接
      imgUrl: list5.value[current.value], // 分享图标
    });
  })
  jweixin.error((res) => {
    console.log(res)
    // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
    // getSignature()
  })
}
const h5Share = () => {
  wxShareTip.value = true
}
const shareClick = () => {
  wxShareTip.value = false
}
const handleChange = (e) => {
  console.log("handleChange", e)
  current.value = e.current
}
const onClickImg = () => {
  uni.previewImage({
    urls: list5.value,
    current: current.value
  })
}
const copyCode = () => {
  uni.setClipboardData({
    data: temCodContent.value,
    success() {
      uni.hideToast()
      // uni.showToast({title: "邀请码复制成功",icon:'none',duration:1000});
      showCopySuccess.value = true
    }
  })
}
const saveImgH5 = () => {
  uni.showToast({
    title: '长按图片并选择保存到手机',
    icon: 'none',
    duration: 3000
  })
  onClickImg()
}
const isYJJJ = ref(false)
const getPermission = async () => {
  let platform = uni.getSystemInfoSync().platform
  if (platform === 'ios') {
    saveImg()
    return
  }

  const photo = uni.getStorageSync("images")
  if (photo) {
    saveImg()
    return
  }
  uni.showModal({
    title: '提示',
    content: "保存图片需要获取您设备上的相册权限，是否同意授权？",
    confirmText: '同意授权',
    success: async function (res) {
      if (res.confirm) {
        const result = await requestAndroidPermission("android.permission.WRITE_EXTERNAL_STORAGE")
        if (result === 1) {
          uni.setStorageSync("images", true)
          saveImg()
        } else if (result === 0) {
          uni.setStorageSync('images', false)
        } else {
          uni.setStorageSync('images', false)
          isYJJJ.value = true
        }
      }
    }
  })
}
const saveImg = () => {
  uni.showLoading({
    title: '正在下載'
  });
  console.log("list5.value[current.value]", list5.value[current.value])
  uni.downloadFile({
    url: list5.value[current.value],
    success: (res) => {
      conUtils("downloadFile", res)
      if (res.statusCode === 200) {
        uni.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function () {
            uni.showToast({
              title: '保存成功 ',
              icon: 'none',
              duration: 3000
            })
          }
        })
      }
    },
    fail(error) {
      uni.hideLoading()
      uni.showToast({title: '下载失败' + JSON.stringify(error)})
      console.log("error", error)
    }
  });
}
// 分享到微信好友
const handleShareWechat = () => {
  uni.share({
    provider: "weixin",
    scene: "WXSceneSession",
    type: 5,
    miniProgram: {
      id: "gh_45626294c5df",
      path: "/pages/index/index?parent_id=" + userInfoStore.userInfo.id,
      webUrl: BaseURL + '/#/?parent_id=' + userInfoStore.userInfo.id,
      // type: 1
    },
    href: BaseURL + '/#/?parent_id=' + userInfoStore.userInfo.id,
    title: reportData.value.money ? '用领食,我总共节省了' + reportData.value.money + '元,快来看看你的吧' : '点外卖用领食周边购，每餐只要0-5元',
    summary: reportData.value.money ? '用领食,我总共节省了' + reportData.value.money + '元,快来看看你的吧' : '点外卖用领食周边购，每餐只要0-5元',
    imageUrl: list5.value[current.value],
    success: function (res) {
      console.log("success:" + JSON.stringify(res));
    },
    fail: function (err) {
      console.log("fail:" + JSON.stringify(err));
    }
  });
}
// 分享到朋友圈
const handleShareTimeline = () => {
  uni.share({
    provider: "weixin",
    scene: "WXSceneTimeline",
    type: 0,
    miniProgram: {
      id: "gh_45626294c5df",
      path: "/pages/index/index?parent_id=" + userInfoStore.userInfo.id,
      webUrl: BaseURL + '/#/?parent_id=' + userInfoStore.userInfo.id,
      // type: 1
    },
    href: BaseURL + '/#/?parent_id=' + userInfoStore.userInfo.id,
    title: reportData.value.money ? '用领食,我总共节省了' + reportData.value.money + '元,快来看看你的吧' : '点外卖用领食周边购，每餐只要0-5元',
    summary: reportData.value.money ? '用领食,我总共节省了' + reportData.value.money + '元,快来看看你的吧' : '点外卖用领食周边购，每餐只要0-5元',
    imageUrl: list5.value[current.value],
    success: function (res) {
      console.log("success:" + JSON.stringify(res));
    },
    fail: function (err) {
      console.log("fail:" + JSON.stringify(err));
    }
  });
}
// 保存图片
const handleSavePhoto = () => {
  getPermission();
}
const platform = uni.getSystemInfoSync().platform //手机平台
const toLittleRedBook = () => {
  // #ifdef APP-PLUS
  if(platform == "android"){
    plus.runtime.openURL("xhsdiscover://home", function (error) {
      uni.showToast({title: "打开小红书APP失败，请手动打开小红书APP分享", icon: "none", duration: 3000})
    });
  } else {
    plus.runtime.launchApplication({ action: 'xhsdiscover://home' }, function(e) {
      uni.showToast({title: "打开抖音APP失败，请手动打开抖音APP分享", icon: "none", duration: 3000})
    });
  }
  // #endif
  // #ifdef H5 || MP
  uni.showToast({title: "邀请码复制成功,请打开小红书APP分享", icon: 'none', duration: 2000});
  // #endif
  showCopySuccess.value = false
}
const toDouYin = () => {
  // #ifdef APP-PLUS
  if(platform === "'android'"){
    plus.runtime.openURL("snssdk1128://home", function (error) {
      uni.showToast({title: "打开抖音APP失败，请手动打开抖音APP分享", icon: "none", duration: 3000})
    });
  } else {
    plus.runtime.launchApplication({ action: 'snssdk1128://home' }, function(e) {
      uni.showToast({title: "打开抖音APP失败，请手动打开抖音APP分享", icon: "none", duration: 3000})
    });
  }
  // #endif
  // #ifdef H5 || MP
  uni.showToast({title: "邀请码复制成功,请打开抖音APP分享", icon: 'none', duration: 2000});
  // #endif
  showCopySuccess.value = false
}
</script>
<template>
  <u-navbar
      :title="isZLPoster?'分享海报':'获取团员'"
      placeholder
      :titleStyle="isZLPoster?'color:#ffffff':'color:black'"
      :leftIconColor="isZLPoster?'#ffffff':'black'"
      auto-back
      :bgColor="isZLPoster?'#fb7c76':'#FECE37'"
  >
  </u-navbar>
  <view class="swiper_box">
    <view :style="{height:isZLPoster?'1188rpx':'988rpx'}">
      <u-swiper class="content_top"
                :list="list5"
                @change="handleChange"
                :autoplay="true"
                @click="onClickImg()"
                indicator=""
                previousMargin="0"
                nextMargin="0"
                duration="600"
                interval="3800"
                indicatorMode="line"
                show-menu-by-longpress
                circular :height="isZLPoster?'1188rpx':'988rpx'" v-if="list5.length > 0">
      </u-swiper>
    </view>
    <view style="background-color: #FFFFFF;padding: 20rpx;border-radius: 10rpx;margin-top: 20rpx" v-if="!isZLPoster">
      <view style="display: flex;margin: 20rpx 10rpx">
        <view style="flex: 1;font-size: 28rpx">我的邀请码：{{ temCod }}</view>
        <view style="border-radius: 30rpx;background-color: #ffae00;color:#FFFFFF;padding: 5rpx 18rpx;font-size: 26rpx"
              @click="copyCode">
          复制
        </view>
      </view>
      <view style="background-color: #F6F6F6;height: 1px"></view>
      <view style="display:flex;margin: 30rpx 0 20rpx">
        <view class="icon-content">
          <view class="slot-icon">1</view>
        </view>
        <view class="slot-line">···</view>
        <view class="icon-content">
          <view class="slot-icon" style="background-color: #ff8d1a">2</view>
        </view>
        <view class="slot-line">···</view>
        <view class="icon-content">
          <view class="slot-icon" style="background-color: #ff7437">3</view>
        </view>
        <view class="slot-line">···</view>
        <view class="icon-content">
          <view class="slot-icon" style="background-color: #47cb6b">4</view>
        </view>
      </view>
      <view style="display:flex;">
        <view class="line_text">复制邀请码</view>
        <view class="slot-line"></view>
        <view class="line_text">分享给好友</view>
        <view class="slot-line"></view>
        <view class="line_text">好友复制邀请码</view>
        <view class="slot-line"></view>
        <view class="line_text">设置-填写邀请码</view>
      </view>
    </view>
    <view class="share_box">
      <view class="text">分享到</view>
      <view class="wechat_box">
        <!-- #ifdef MP -->
        <view class="small_box">
          <button class="complete1" open-type="share">
            <view class="icon">
              <image :src="BaseImgUrl + '/group/wechat_icon.png'"></image>
            </view>
            <view class="name">微信好友</view>
          </button>
        </view>
        <view class="small_box">
          <button class="complete1" @click="saveImg">
            <view class="icon">
              <image :src="BaseImgUrl + '/group/upload_icon.png'"></image>
            </view>
            <view class="name">保存图片</view>
          </button>
        </view>
        <!-- #endif -->
        <!-- #ifdef APP-PLUS -->
        <view class="small_box" @click="handleShareWechat()">
          <view class="icon">
            <image :src="BaseImgUrl + '/group/wechat_icon.png'"></image>
          </view>
          <view class="name">微信好友</view>
        </view>
        <!--        <view class="small_box" @click="handleShareTimeline()">-->
        <!--          <view class="icon">-->
        <!--            <image :src="BaseImgUrl + '/group/pyq_icon.png'"></image>-->
        <!--          </view>-->
        <!--          <view class="name">朋友圈</view>-->
        <!--        </view>-->
        <view class="small_box" @click="handleSavePhoto()">
          <view class="icon">
            <image :src="BaseImgUrl + '/group/upload_icon.png'"></image>
          </view>
          <view class="name">保存图片</view>
        </view>
        <view class="small_box" @click="handleShareWechat()">
          <view class="icon">
            <image :src="BaseImgUrl + '/group/share_icon.png'"></image>
          </view>
          <view class="name">分享链接</view>
        </view>
        <!-- #endif -->
        <!-- #ifdef H5 -->
        <view class="small_box" @click="h5Share()">
          <view class="icon">
            <image :src="BaseImgUrl + '/group/wechat_icon.png'"></image>
          </view>
          <view class="name">微信好友</view>
        </view>
        <view class="small_box" @click="h5Share()">
          <view class="icon">
            <image :src="BaseImgUrl + '/group/pyq_icon.png'"></image>
          </view>
          <view class="name">朋友圈</view>
        </view>
        <view class="small_box" @click="saveImgH5">
          <view class="icon">
            <image :src="BaseImgUrl + '/group/upload_icon.png'"></image>
          </view>
          <view class="name">保存图片</view>
        </view>
        <!-- #endif -->
      </view>
    </view>
    <!-- #ifdef H5 -->
    <view class="share_box_shadow" v-if="wxShareTip" @click="shareClick">
      <image mode="widthFix" :src="BaseImgUrl + '/images/share_line.png'"></image>
    </view>
    <!-- #endif -->
    <u-safe-bottom></u-safe-bottom>
  </view>
  <u-popup :show="showCopySuccess" mode="center" :safeAreaInsetBottom="false" round="10"
           @close="showCopySuccess = false">
    <view class="wm_box">
      <view class="content_boxs">
        <view style="position: relative">
          <view class="know_t">复制邀请码成功</view>
          <view style="position: absolute;top: 16rpx;right: 16rpx" @click="showCopySuccess = false">
            <u-icon name="close"></u-icon>
          </view>
        </view>
        <view style="font-size: 28rpx;margin-top: 30rpx;line-height: 46rpx">分享给好友，成功绑定邀请码成为团员，下单你至多可得
          <text class="money">23元奖励</text>；
        </view>
        <view style="display: flex;margin-top: 36rpx">
          <view style="flex: 1"></view>
          <!-- #ifdef MP -->
          <button class="small_box" style="text-align: center;background: white;" open-type="share">
            <view class="icon">
              <image :src="BaseImgUrl + '/group/wechat_icon.png'"></image>
            </view>
            <view class="name" style="margin-top: -10rpx">微信</view>
          </button>
          <view style="flex: 1"></view>
          <button class="small_box" style="text-align: center;background: white;" @click="toLittleRedBook">
            <view class="icon">
              <image :src="BaseImgUrl + '/group/xiaohongshu.png'"></image>
            </view>
            <view class="name" style="margin-top: -10rpx">小红书</view>
          </button>
          <view style="flex: 1"></view>
          <button class="small_box" style="text-align: center;background: white;" @click="toDouYin">
            <view class="icon">
              <image :src="BaseImgUrl + '/group/douyin.png'"></image>
            </view>
            <view class="name" style="margin-top: -10rpx">抖音</view>
          </button>
          <!-- #endif -->
          <!-- #ifdef APP-PLUS -->
          <button class="small_box" style="text-align: center;background: white;" @click="handleShareWechat()">
            <view class="icon">
              <image :src="BaseImgUrl + '/group/wechat_icon.png'"></image>
            </view>
            <view class="name" style="margin-top: -10rpx">微信</view>
          </button>
          <view style="flex: 1"></view>
          <button class="small_box" style="text-align: center;background: white;" @click="toLittleRedBook">
            <view class="icon">
              <image :src="BaseImgUrl + '/group/xiaohongshu.png'"></image>
            </view>
            <view class="name" style="margin-top: -10rpx">小红书</view>
          </button>
          <view style="flex: 1"></view>
          <button class="small_box" style="text-align: center;background: white;" @click="toDouYin">
            <view class="icon">
              <image :src="BaseImgUrl + '/group/douyin.png'"></image>
            </view>
            <view class="name" style="margin-top: -10rpx">抖音</view>
          </button>
          <!-- #endif -->
          <!-- #ifdef H5 -->
          <button class="small_box" style="text-align: center;background: white" @click="h5Share()">
            <view class="icon">
              <image :src="BaseImgUrl + '/group/wechat_icon.png'"></image>
            </view>
            <view class="name" style="margin-top: -10rpx">微信</view>
          </button>
          <view style="flex: 1"></view>
          <button class="small_box" style="text-align: center;background: white" @click="toLittleRedBook">
            <view class="icon">
              <image :src="BaseImgUrl + '/group/xiaohongshu.png'"></image>
            </view>
            <view class="name" style="margin-top: -10rpx">小红书</view>
          </button>
          <view style="flex: 1"></view>
          <button class="small_box" style="text-align: center;background: white" @click="toDouYin">
            <view class="icon">
              <image :src="BaseImgUrl + '/group/douyin.png'"></image>
            </view>
            <view class="name" style="margin-top: -10rpx">抖音</view>
          </button>
          <!-- #endif -->
          <view style="flex: 1"></view>
        </view>
        <view style="font-size: 22rpx;margin-top: 30rpx;color: #999999;width: 100%;text-align: center">
          也可以分享到其他平台
        </view>
      </view>
    </view>
  </u-popup>
</template>
<style lang="scss">
page {
  background-color: #F6F6F6;
}

.u-status-bar,
.u-navbar__content {
  background-image: linear-gradient(90deg, #FECE37, #FECE37);
}
uni-button:after{
  border-color: #FFFFFF !important;
}

</style>
<style lang="scss" scoped>
.wm_box {
  position: relative;
  width: 600rpx;
  background: #ffffff;
  border-radius: 32.5rpx;
  margin: 0 auto 0;
}

.content_boxs {
  box-sizing: border-box;
  position: relative;
  margin: 30rpx;

  .know_t {
    font-size: 32rpx;
    color: #000;
    text-align: center;
    box-sizing: border-box;
    padding: 10rpx 0 20rpx;
    border-bottom: 1px solid #eee;
  }

  .money {
    color: #ff850b;
  }

  .small_box {
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 26rpx;

    image {
      width: 68rpx;
      height: 68rpx;
      margin-bottom: 10rpx;
    }
  }
}

.icon-content {
  width: 130rpx;
}

.slot-icon {
  margin: auto;
  width: 38rpx;
  height: 38rpx;
  background-color: $u-warning;
  border-radius: 100px;
  font-size: 22rpx;
  color: #fff;
  line-height: 38rpx;
  text-align: center;
}

.slot-line {
  color: $u-warning;
  font-size: 22rpx;
  font-weight: bold;
  line-height: 38rpx;
  text-align: center;
  flex: 1;
}

.line_text {
  width: 130rpx;
  text-align: center;
  font-size: 22rpx;
}

.share_box_shadow {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 99999;
  background-color: rgba(0, 0, 0, 0.6);
}

.share_box_shadow image {
  max-width: 80%;
  margin: 10%;
}

.complete1 {
  font-weight: bold;
  font-size: 36rpx;
  line-height: 92rpx;
  text-align: center;
  background: white;
}

.swiper_box {
  box-sizing: border-box;
  padding: 20rpx;

  .share_box {
    margin-top: 10rpx;
    border-radius: 10rpx;
    box-sizing: border-box;
    padding: 30rpx 30rpx 0;
    background-color: #fff;
    height: 292rpx;

    .text {
      font-size: 28rpx;
      color: #333;
    }

    .wechat_box {
      display: flex;
      justify-content: space-between;
      // align-items: center;
      text-align: center;
      margin-top: 42rpx;

      .small_box {
        flex: 1;

        .icon {
          width: 64rpx;
          height: 64rpx;
          margin: 0 auto;

          image {
            width: 100%;
            height: 100%;
          }
        }

        .name {
          font-size: 26rpx;
          color: #333;
          margin-top: 10rpx;
        }
      }
    }
  }
}
</style>
